//
//  Emoji.m
//  TestNIMSDK
//
//  Created by jianyong.wang on 2017/6/1.
//  Copyright © 2017年 jianyong.wang. All rights reserved.
//

#import "JYInputView.h"
#import "JYEmojiManager.h"
#import "JYCollectionViewFlowLayout.h"
#import "macros.h"
#import "JYTextView.h"
#import "NSAttributedString+EmojiExtension.h"
#import "EmojiTextAttachment.h"
@interface JYInputView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextViewDelegate,JYTextViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *textViewSuperView;
@property (weak, nonatomic) IBOutlet JYTextView *textview;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;

@property (weak, nonatomic) IBOutlet UICollectionView *collection;
@property(nonatomic,assign) CGRect myFrame;
@property(assign,nonatomic)CGRect keyBoardRect;
@property(nonatomic,assign)CGRect tempRect;
@property(nonatomic,assign)BOOL keyboardUp;//键盘已弹起标志
@end
@implementation JYInputView
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self = [[NSBundle mainBundle]loadNibNamed:NSStringFromClass([self class]) owner:self options:nil].lastObject;
        [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class])];
       JYCollectionViewFlowLayout * layout = [[JYCollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.rowCount = 3;
        layout.itemCountPerRow = 8;
        self.collection.collectionViewLayout = layout;
        self.collection.dataSource = self;
        self.collection.delegate = self;
        self.collection.pagingEnabled = YES;
        self.myFrame = frame;//获取xib视图时，重写drawinrect方法中使用
        self.textview.delegate = self;//计算当激活键盘时，其在俯视图上面的位置
        self.textview.jy_Delegate = self;//监听删除按钮
        [self addObserverListen];
    }
    return self;
}

-(void)addObserverListen
{
    //注册通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //注册通知,监听键盘消失事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}
-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    self.frame = self.myFrame;
}
- (IBAction)emojiButtonClick:(UIButton *)sender {
    [UIView animateWithDuration:.3 animations:^{
        self.transform = (!self.keyboardUp && CGRectGetMaxY(self.frame)==kScreenHeight)?CGAffineTransformIdentity:CGAffineTransformMakeTranslation( 0, -210);
    }];
    //需要将键盘落下标志位放在后面，因为键盘落下需要一定的时间，确保首次落下后标志位置为false，下一次就可以落下表情键盘了
    [self.textview resignFirstResponder];
}
- (IBAction)sendButtonClick:(id)sender {
    /**
     1、当输入框中不显示文本，显示对应的表情时，在发送消息时，需要转换为文本形式 '[大笑]'
     */
      NSString * string =  [self.textview.textStorage getPlainString];
      if (self.textview.text.length > 0 && self.send) {
                    self.send(string);
                }
    
    /**
     2、当输入框中显示文本，不显示对应的表情时，在发送消息时，不需要转换
     */
//    NSString * string = self.textview.text;
//    [UIView animateWithDuration:.3 animations:^{
//        self.transform = CGAffineTransformIdentity;
//    }];
//    if (self.textview.text.length > 0 && self.send) {
//        self.send(string);
//    }
//    self.textview.text =@"";
//    [self.textview.textStorage deleteCharactersInRange:NSMakeRange(0, self.textview.textStorage.length)];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.collection) {
        NSInteger index = scrollView.contentOffset.x / 375;
        self.pageControl.currentPage = index;
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [JYEmojiManager sharedManager].catalogs.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Emoticon * emotico = [JYEmojiManager sharedManager].catalogs[indexPath.item];
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class]) forIndexPath:indexPath];
    while (cell.contentView.subviews.lastObject != nil) {
        [cell.contentView.subviews.lastObject removeFromSuperview];
    }
    UIImageView * label = [[UIImageView alloc]initWithFrame:(CGRect){0,0,30,30}];
    label.image = [UIImage imageNamed:emotico.filename];
    [cell.contentView addSubview:label];
    return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(30, 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(10, (375-8*30)/8.0/2.0, 10, (375-8*30)/8.0/2.0);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return (375-8*30)/8.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return (150-20-3*30)/2.0;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Emoticon * con = [JYEmojiManager sharedManager].catalogs[indexPath.item];
    if ([con.tag isEqualToString:@"删除"]) {
        //判断最后一个为】 删除表情
        if([self.textview.text hasSuffix:@"]"])
        {
            self.textview.text = [self.textview.text substringToIndex:[[JYEmojiManager sharedManager]rangOfLastEmotion:self.textview.text]];
            NSLog(@"------>%@",self.textview.text);
        }else self.textview.text =self.textview.text.length>0? [self.textview.text substringToIndex:self.textview.text.length-1]:@"";
    }else if (con.tag.length){
        [self setTextViewInfo:con];
    }
    
}
-(void)setTextViewInfo:(Emoticon *)con
{
    
    /**
     1、将表情文本转换为图片形式展示在textview ，实际就是操作NSMutableAttributedString
     */
    EmojiTextAttachment *attachment = [[EmojiTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:con.filename];
    attachment.emojiSize = CGSizeMake(15, 15);
    attachment.emojiTag = con.tag;
    NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];
    NSRange selectedRange = self.textview.selectedRange;
    if (selectedRange.length > 0) {
        [self.textview.textStorage deleteCharactersInRange:selectedRange];
    }
    [self.textview.textStorage appendAttributedString:attachmentString];
    self.textview.selectedRange = NSMakeRange(self.textview.selectedRange.location+1, 0);
    [self.textview scrollRectToVisible:CGRectMake(0, self.textview.contentSize.height-15, self.textview.contentSize.width, 10) animated:YES];
    
    
    /**
     2、当输入框中显示文本，不显示对应的表情时，在发送消息时，不需要转换，直接插入即可
     */
//    [self.textview insertText:con.tag];
//    //当直接设置uitextview的文本时，不会自动偏移到最下面，需要手动设置，
//    [self.textview scrollRectToVisible:CGRectMake(0, self.textview.contentSize.height-15, self.textview.contentSize.width, 10) animated:YES];
}
#pragma mark - textview代理
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.tempRect = [textView.superview convertRect:textView.superview.bounds toView:self.superview];
    return YES;
}
-(void)jyTextViewDeleteBackward:(JYTextView *)textview
{
    NSLog(@"删除出");
    [[JYEmojiManager sharedManager]deleteString:textview];
}
#pragma mark - keyboard
-(void)keyboardDidShow:(NSNotification *)notification
{
    self.keyBoardRect=[notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        
        CGFloat Y = CGRectGetMaxY(self.tempRect) -  ( kScreenHeight - CGRectGetHeight(self.keyBoardRect));
        Y = Y<0 ? 0: Y;
        self.transform = CGAffineTransformTranslate(self.transform, 0, -Y);
    }];
    self.keyboardUp = YES;
}
-(void)keyboardDidHidden:(NSNotification *)notification
{
    
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
    } completion:^(BOOL finished) {
    }];
    self.keyboardUp = NO;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
